package com.sihai.ehr.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.sihai.core.DataAccessor;
import com.sihai.core.DynamicQuery;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.QueryCreator;
import com.sihai.core.Sorter;
import com.sihai.core.beans.Property;
import com.sihai.ehr.model.biz.ContractPerson;
import com.sihai.ehr.model.biz.ContractSign;
import com.sihai.ehr.model.biz.ContractSignAuditing;
import com.sihai.ehr.model.biz.ContractSignRt;
import com.sihai.ehr.model.biz.ContractSignRtt;
import com.sihai.ehr.model.biz.ContractSignZz;
import com.sihai.ehr.model.biz.ContractVersion;
import com.sihai.ehr.model.biz.ContractVersionAuditing;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.repository.AuditingRepository;
import com.sihai.ehr.service.ContractService;
import com.sihai.ehr.utils.DateUtil;
import com.sihai.ehr.web.pojo.ContractSignPojo;
import com.sihai.ehr.web.pojo.ContractSignPojo2;
import com.sihai.ehr.web.pojo.ContractSignViewPojo;


@Service("contractService")
public class ContractServiceImpl implements ContractService {
    @Resource
    private DataAccessor dataAccessor;

    @Resource
    private AuditingRepository auditingRepository;

    @Property("contract_resign_date")
    private int contract_resign_date;

    @Override
    public ContractVersion getVersion(Long id) {
        if (id == null) {
            return null;
        }

        return dataAccessor.get(ContractVersion.class, id);
    }

    @Override
    public void saveVersion(ContractVersion version) {
        if (version == null) {
            return;
        }
        boolean isCreate = (version.getId() == null || version.getId() <= 0);
        dataAccessor.save(version);
        if(isCreate){
            saveContractVersionAuditings(version, 1);
        }
    }

    @Override
    public void removeVersion(final String ids) {
        if (StringUtils.isBlank(ids)) {
            return;
        }

        dataAccessor.batchUpdate(new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                return session.createQuery(String
                        .format("update ContractVersion v set v.cancel = 1 where v.id in (%s)",
                        ids));
            }
        });
    }

    @Override
    public LimitedList<ContractVersion> findVersions(final ContractVersion version, Limit limit, Sorter sorter) {
        return dataAccessor.findByQuery(ContractVersion.class,
                new QueryCreator() {
                    @Override
                    public Query createQuery(Session session) {
                        DynamicQuery dynamicQuery = new DynamicQuery("from ContractVersion v where 1=1 ");
                        dynamicQuery.appendIfNotNull("and v.cancel = :cancel", "cancel", version.getCancel());
                        dynamicQuery.appendIfNotNull("and v.auditStatus = :status", "status", version.getAuditStatus());
                        if (version.getOrganization() != null && version.getOrganization().getId() != null) {
                            Organization organization = dataAccessor.get(Organization.class, version.getOrganization().getId());
                            if (organization != null) {
                                Long oid = null;
                                if (organization.getTopOrganization() == null) {
                                    oid = organization.getId();
                                } else {
                                    oid = organization.getTopOrganization().getId();
                                }
                                dynamicQuery.appendIfNotNull("and v.organization.id = :orgId", "orgId", oid);
                            }
                        }
                        return dynamicQuery.build(session);
                    }
                }, limit, sorter);
    }

    @Override
    public LimitedList<ContractVersion> findVersionsByOrganizationId(Long organizationId, Limit limit, Sorter sorter) {
        Organization organization = dataAccessor.get(Organization.class, organizationId);
        Long oid = organizationId;
        if (organization.getTopOrganization() == null) {
            oid = organization.getId();
        } else {
            oid = organization.getTopOrganization().getId();
        }
        return dataAccessor.findByHql(ContractVersion.class, "select new ContractVersion(id, contractName) from ContractVersion where cancel <> 1 and organization.id = ?", new Object[]{oid}, limit, sorter);
    }

    @Override
    public LimitedList<ContractVersion> findVersionsByDutyId(Long dutyId,
                                                             Limit limit, Sorter sorter) {
        if (dutyId == null) {
            return null;
        }
        return dataAccessor
                .findByHql(
                        ContractVersion.class,
                        "select p.contractVersion from ContractPerson p where p.duty.id = ?",
                        new Object[]{dutyId}, limit, sorter);
    }

    @Override
    public ContractPerson getPerson(Long id) {
        if (id == null) {
            return null;
        }
        return dataAccessor.get(ContractPerson.class, id);
    }

    @Override
    public ContractPerson getContractPersonByDutyId(Long dutyId) {
        if (dutyId == null || dutyId <= 0) {
            throw new RuntimeException("【参数异常】【dutyId参数有误】");
        }
        try {
            List<ContractPerson> contractPersons = dataAccessor.findByHql(
                    ContractPerson.class,
                    "from ContractPerson c where c.duty.id = ?",
                    new Object[]{dutyId}, null, null);
            if (contractPersons != null && contractPersons.size() > 0) {
                return contractPersons.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException("【根据职务编号获取合同版本关联信息异常】【异常原因："
                    + e.getMessage()
                    + "】【错误地点：ContractServerImpl.getContractPersonByDutyId】");
        }
    }

    @Override
    public void savePerson(ContractPerson person) {
        if (person == null) {
            return;
        }
        dataAccessor.save(person);
    }

    @Override
    public LimitedList<ContractPerson> findPersonsByOrganizationId(
            Long organizationId, Limit limit, Sorter sorter) {
        return dataAccessor
                .findByHql(
                        ContractPerson.class,
                        "from ContractPerson p where p.cancel <> 1 and p.duty.organization.id = ?",
                        new Object[]{organizationId}, limit, sorter);
    }

    @Override
    public void removePersons(final String ids) {
        if (StringUtils.isBlank(ids)) {
            return;
        }

        dataAccessor.batchUpdate(new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                return session.createQuery(String
                        .format("update ContractPerson p set p.cancel = 1 where p.id in (%s)",
                        ids));
            }
        });
    }

    //得到合同签订审核、合同人员查看列表
    @Override
    public LimitedList<ContractSignPojo2> findForContractSignAudit(Long organizationId, String type, Limit limit, Sorter sorter) {
        Assert.notNull(organizationId, "organizationId is required");
        String temp = "";
        /*if(StringUtils.equals("view", type)){
            temp = " and s.auditStatus='pass_audit'";
        }*/
        LimitedList<EmployeeinfoWork> works = dataAccessor.findByHql(EmployeeinfoWork.class, "select distinct w from EmployeeinfoWork w, ContractPerson p where w.organization.id = ? and w.duty = p.duty", new Object[]{organizationId}, limit, sorter);
        if(works != null && !works.isEmpty()){
            LimitedList<ContractSignPojo2> pojos = new LimitedList<ContractSignPojo2>(works.size());
            Map<Long, List<ContractVersion>> map = new HashMap<Long, List<ContractVersion>>();
            for(EmployeeinfoWork work : works){
                ContractSignPojo2 pojo = new ContractSignPojo2();
                List<ContractVersion> versions = null;
                if(map.containsKey(work.getDuty().getId())){
                    versions = map.get(work.getDuty().getId());
                }else{
                    versions = dataAccessor.findByHql(ContractVersion.class, "select p.contractVersion from ContractPerson p where p.duty=? and p.contractVersion.cancel is not true", new Object[]{work.getDuty()}, null, null);
                    map.put(work.getDuty().getId(), versions);
                }
                pojo.setWork(work);
                pojo.setVersions(versions);
                int state = 0; //0为未输入，输入后状态为1未审核, 开始审核为2审核中, 审核完成后是3未签， 签订后是4已签， 需续签时是5续签, 续签后历史合同状态为6已过期, 该合同状态为7已续签
                int[] states = new int[8];
                if(versions != null && !versions.isEmpty()){
                    for(ContractVersion version : versions){
                        if(StringUtils.equals("contract_template1", version.getContractTemplate())){
                            List<ContractSign> signs = dataAccessor.findByHql(ContractSign.class, "from ContractSign s where s.version = ? and s.employeeinfoBase=? and s.state <> 6"+temp, new Object[]{version, work.getBaseId()}, null,null);
                            if(signs != null && !signs.isEmpty()){
                                ContractSign sign = signs.get(0);
                                if(sign.getAuditStatus() == AuditStatus.pass_audit){
                                    Long endDays = DateUtil.getDayToCurrdate(sign.getEndDate());
                                    if(contract_resign_date <= 0){
                                        contract_resign_date = 30;
                                    }
                                    if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                                        states[5] = states[5]+1;
                                        continue;
                                    }
                                }
                                int s = sign.getState();
                                if(s>=1 && s<=7){
                                    states[s] = states[s]+1;
                                }
                            }else{
                                states[0] = states[0]+1;
                            }
                        }else if (StringUtils.equals("contract_template2", version.getContractTemplate())){
                            List<ContractSignZz> signZzs = dataAccessor.findByHql(ContractSignZz.class, "from ContractSignZz s where s.version = ? and s.employeeinfoBase=? and s.state <> 6"+temp, new Object[]{version, work.getBaseId()}, null,null);
                            if(signZzs != null && !signZzs.isEmpty()){
                                ContractSignZz signZz = signZzs.get(0);
                                if(signZz.getAuditStatus() == AuditStatus.pass_audit){
                                    Long endDays = DateUtil.getDayToCurrdate(signZz.getEndDate());
                                    if(contract_resign_date <= 0){
                                        contract_resign_date = 30;
                                    }
                                    if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                                        states[5] = states[5]+1;
                                        continue;
                                    }
                                }
                                int s = signZz.getState();
                                if(s>=1 && s<=7){
                                    states[s] = states[s]+1;
                                }
                            }else{
                                states[0] = states[0]+1;
                            }
                        }else if (StringUtils.equals("contract_template3", version.getContractTemplate())){
                            List<ContractSignRt> signRts = dataAccessor.findByHql(ContractSignRt.class, "from ContractSignRt s where s.version = ? and s.employeeinfoBase=? and s.state <> 6"+temp, new Object[]{version, work.getBaseId()}, null,null);
                            if(signRts != null && !signRts.isEmpty()){
                                ContractSignRt signRt = signRts.get(0);
                                if(signRt.getAuditStatus() == AuditStatus.pass_audit){
                                    Long endDays = DateUtil.getDayToCurrdate(signRt.getEndDate());
                                    if(contract_resign_date <= 0){
                                        contract_resign_date = 30;
                                    }
                                    if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                                        states[5] = states[5]+1;
                                        continue;
                                    }
                                }
                                int s = signRt.getState();
                                if(s>=1 && s<=7){
                                    states[s] = states[s]+1;
                                }
                            }else{
                                states[0] = states[0]+1;
                            }
                        }else if (StringUtils.equals("contract_template4", version.getContractTemplate())){
                            List<ContractSignRtt> signRtts = dataAccessor.findByHql(ContractSignRtt.class, "from ContractSignRtt s where s.version = ? and s.employeeinfoBase=? and s.state <> 6"+temp, new Object[]{version, work.getBaseId()}, null,null);
                            if(signRtts != null && !signRtts.isEmpty()){
                                ContractSignRtt signRtt = signRtts.get(0);
                                if(signRtt.getAuditStatus() == AuditStatus.pass_audit){
                                    Long endDays = DateUtil.getDayToCurrdate(signRtt.getEndDate());
                                    if(contract_resign_date <= 0){
                                        contract_resign_date = 30;
                                    }
                                    if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                                        states[5] = states[5]+1;
                                        continue;
                                    }
                                }
                                int s = signRtt.getState();
                                if(s>=1 && s<=7){
                                    states[s] = states[s]+1;
                                }
                            }else{
                                states[0] = states[0]+1;
                            }
                        }
                    }
                }
                int index = 0;
                for(int i=0; i<states.length; i++){
                    if(states[i] > 0){
                        index = i;
                        break;
                    }
                }
                //0为未输入，输入后状态为1未审核, 开始审核为2审核中, 审核完成后是3未签， 签订后是4已签， 需续签时是5续签, 续签后历史合同状态为6已过期, 该合同状态为7已续签
                //续签优先于已签
                if(index == 4 && states[5] > 0){
                    index = 5;
                }
                pojo.setStatus(index);
                pojo.setContractCount(states[index]);
                pojos.add(pojo);
            }
            return pojos;
        }
        return null;
    }

    public LimitedList<ContractSignPojo> findForContractSignAudit_bak(
            Long organizationId, Limit limit, Sorter sorter) {
        LimitedList<EmployeeinfoWork> works = dataAccessor
                .findByHql(
                        EmployeeinfoWork.class,
                        "select distinct w from EmployeeinfoWork w, ContractPerson p where w.organization.id = ? and w.duty = p.duty",
                        new Object[]{organizationId}, limit, sorter);
        if (works != null && !works.isEmpty()) {
            LimitedList<ContractSignPojo> contractSignPojos = new LimitedList<ContractSignPojo>();
            int count = works.size();
            for (EmployeeinfoWork work : works) {
                ContractSignPojo sign = new ContractSignPojo();
                sign.setWork(work);

                // 查找该员工的岗位对应的合同名
                List<String> contractNames = dataAccessor
                        .findByHql(
                                String.class,
                                "select p.contractVersion.contractName from ContractPerson p where p.duty = ?",
                                new Object[]{work.getDuty()}, null, null);
                if (contractNames != null && !contractNames.isEmpty()) {
                    StringBuffer sb = new StringBuffer();
                    int size = contractNames.size();
                    for (int i = 0; i < size; i++) {
                        sb.append(contractNames.get(i));
                        if (i < size - 1) {
                            sb.append(",");
                        }
                    }
                    sign.setContractType(sb.toString());
                }

                // 查找该员工是否签订合同信息
                List<ContractSign> signs = dataAccessor
                        .findByHql(
                                ContractSign.class,
                                "select new ContractSign(s.id,s.state) from ContractSign s where s.cancel <> '1' and s.employeeinfoBase = ?",
                                new Object[]{work.getBaseId()}, null, null);

                if (signs != null && !signs.isEmpty()) {
                    for (ContractSign temp : signs) {
                        ContractSignPojo pojotemp = new ContractSignPojo();
                        pojotemp.setWork(sign.getWork());
                        pojotemp.setContractType(sign.getContractType());
                        pojotemp.setContractSignId(temp.getId());
                        pojotemp.setState(temp.getState());
                        pojotemp.setContractCount(signs.size());
                        contractSignPojos.add(pojotemp);
                        count++;
                    }
                    count--;
                } else {
                    contractSignPojos.add(sign);
                }
            }
            contractSignPojos.setTotalcount(count);
            System.out.println("=============="+count);
            return contractSignPojos;
        }
        return null;
    }

    @Override
    public ContractSignPojo findForContractSignAuditByEmpolyeeId(Long organizationId, Long empolyeeId) {
        LimitedList<EmployeeinfoWork> works = dataAccessor
                .findByHql(
                        EmployeeinfoWork.class,
                        "select distinct w from EmployeeinfoWork w, ContractPerson p where w.organization.id = ? and w.duty = p.duty and w.baseId.id=?",
                        new Object[]{organizationId, empolyeeId}, null, null);
        if (works != null && !works.isEmpty() && works.size() > 0) {
            int count = works.size();
            ContractSignPojo sign = new ContractSignPojo();
            EmployeeinfoWork work = works.get(0);
            sign.setWork(work);
            // 查找该员工的岗位对应的合同名
            List<String> contractNames = dataAccessor
                    .findByHql(
                            String.class,
                            "select p.contractVersion.contractName from ContractPerson p where p.duty = ?",
                            new Object[]{work.getDuty()}, null, null);
            if (contractNames != null && !contractNames.isEmpty()) {
                StringBuffer sb = new StringBuffer();
                int size = contractNames.size();
                for (int i = 0; i < size; i++) {
                    sb.append(contractNames.get(i));
                    if (i < size - 1) {
                        sb.append(",");
                    }
                }
                sign.setContractType(sb.toString());
            }

            // 查找该员工是否签订合同信息
            List<Object[]> signs = dataAccessor
                    .findByHql(
                            Object[].class,
                            "select s.id, s.state from ContractSign s where s.cancel <> '1' and s.employeeinfoBase = ?",
                            new Object[]{work.getBaseId()}, null, null);
            if (signs != null && !signs.isEmpty()) {
                Object[] objects = signs.get(0);
                sign.setContractSignId((Long) objects[0]);
                int state = (Integer) objects[1];
//                if (state == 0) {
//                    count--;
//                      continue;
//                }
                sign.setState(state);
                sign.setContractCount(signs.size());
            }
            ;
            return sign;
        }
        return null;
    }

    @Override
    public ContractSignPojo2 findForContractSignAuditByEmpolyeeId2(Long organizationId, Long workId) throws Exception{
        Assert.notNull(workId, "workId is required");
        EmployeeinfoWork work  = dataAccessor.get(EmployeeinfoWork.class, workId);
        Assert.notNull(work, "work is required");
        List<ContractVersion> versions = dataAccessor.findByHql(ContractVersion.class, "select p.contractVersion from ContractPerson p where p.duty=? and p.contractVersion.cancel is not true", new Object[]{work.getDuty()}, null, null);
        List<ContractSign> signs = dataAccessor.findByHql(ContractSign.class, "select new ContractSign(s.id, s.employeeinfoBase, s.auditStatus, s.version, s.state, s.endDate) from ContractSign s where s.employeeinfoBase=? and s.state <> 6", new Object[]{work.getBaseId()}, null,null);
        List<ContractSignZz> signZzs = dataAccessor.findByHql(ContractSignZz.class, "select new ContractSignZz(s.id, s.employeeinfoBase, s.auditStatus, s.version, s.state, s.endDate) from ContractSignZz s where s.employeeinfoBase=? and s.state <> 6", new Object[]{work.getBaseId()}, null,null);
        List<ContractSignRt> signRts = dataAccessor.findByHql(ContractSignRt.class, "select new ContractSignRt(s.id, s.employeeinfoBase, s.auditStatus, s.version, s.state, s.endDate) from ContractSignRt s where s.employeeinfoBase=? and s.state <> 6", new Object[]{work.getBaseId()}, null,null);
        List<ContractSignRtt> signRtts = dataAccessor.findByHql(ContractSignRtt.class, "select new ContractSignRtt(s.id, s.employeeinfoBase, s.auditStatus, s.version, s.state, s.endDate) from ContractSignRtt s where s.employeeinfoBase=? and s.state <> 6", new Object[]{work.getBaseId()}, null,null);
        
        ContractSignPojo2 pojo = new ContractSignPojo2();
        pojo.setWork(work);
        pojo.setVersions(versions);
        pojo.setSigns(signs);
        pojo.setSignZzs(signZzs);
        pojo.setSignRts(signRts);
        pojo.setSignRtts(signRtts);
        if(versions != null && !versions.isEmpty()){
            for(ContractVersion v : versions){
                organizationId = v.getOrganization().getId();
                if(StringUtils.equals("contract_template1", v.getContractTemplate()) && signs != null && !signs.isEmpty()){
                    for(ContractSign sign : signs){
                        if(sign.getVersion().getId().longValue() == v.getId().longValue()){
                            v.setSign(sign);
                            break;
                        }
                    }
                    if(v.getSign() != null && v.getSign().getId() != null){
                        if(v.getSign().getAuditStatus() == AuditStatus.pass_audit){
                            Long endDays = DateUtil.getDayToCurrdate(v.getSign().getEndDate());
                            if(contract_resign_date <= 0){
                                contract_resign_date = 30;
                            }
                            if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                                v.getSign().setState(5);
                            }
                        }

                        Long contractSignId = v.getSign().getId();
                        List<List<ContractSignAuditing>> audits = findContractSignAuditing("sign", contractSignId);
                        if (audits == null || audits.isEmpty()) {
                            saveContractSignAuditingProcess("sign", contractSignId);
                            audits = findContractSignAuditing("sign", contractSignId);
                        }
                        v.setAudits(audits);
                    }
                }else if(StringUtils.equals("contract_template2", v.getContractTemplate()) && signZzs != null && !signZzs.isEmpty()){
                    for(ContractSignZz sign : signZzs){
                        if(sign.getVersion().getId().longValue() == v.getId().longValue()){
                            v.setSignZz(sign);
                            break;
                        }
                    }
                    if(v.getSignZz() != null && v.getSignZz().getId() != null){
                        Long endDays = DateUtil.getDayToCurrdate(v.getSignZz().getEndDate());
                        if(contract_resign_date <= 0){
                            contract_resign_date = 30;
                        }
                        if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                            v.getSignZz().setState(5);
                        }
                        Long contractSignZzId = v.getSignZz().getId();
                        List<List<ContractSignAuditing>> audits = findContractSignAuditing("signZz", contractSignZzId);
                        if (audits == null || audits.isEmpty()) {
                            saveContractSignAuditingProcess("signZz", contractSignZzId);
                            audits = findContractSignAuditing("signZz", contractSignZzId);
                        }
                        v.setAudits(audits);
                    }
                }
                //@{ added by henry
                else if(StringUtils.equals("contract_template3", v.getContractTemplate()) && signRts != null && !signRts.isEmpty()){
                    for(ContractSignRt sign : signRts){
                        if(sign.getVersion().getId().longValue() == v.getId().longValue()){
                            v.setSignRt(sign);
                            break;
                        }
                    }
                    if(v.getSignRt() != null && v.getSignRt().getId() != null){
                        Long endDays = DateUtil.getDayToCurrdate(v.getSignRt().getEndDate());
                        if(contract_resign_date <= 0){
                            contract_resign_date = 30;
                        }
                        if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                            v.getSignRt().setState(5);
                        }
                        Long contractSignRtId = v.getSignRt().getId();
                        List<List<ContractSignAuditing>> audits = findContractSignAuditing("signRt", contractSignRtId);
                        if (audits == null || audits.isEmpty()) {
                            saveContractSignAuditingProcess("signRt", contractSignRtId);
                            audits = findContractSignAuditing("signRt", contractSignRtId);
                        }
                        v.setAudits(audits);
                    }
                }else if(StringUtils.equals("contract_template4", v.getContractTemplate()) && signRtts != null && !signRtts.isEmpty()){
                    for(ContractSignRtt sign : signRtts){
                        if(sign.getVersion().getId().longValue() == v.getId().longValue()){
                            v.setSignRtt(sign);
                            break;
                        }
                    }
                    if(v.getSignRtt() != null && v.getSignRtt().getId() != null){
                        Long endDays = DateUtil.getDayToCurrdate(v.getSignRtt().getEndDate());
                        if(contract_resign_date <= 0){
                            contract_resign_date = 30;
                        }
                        if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                            v.getSignRtt().setState(5);
                        }
                        Long contractSignRttId = v.getSignRtt().getId();
                        List<List<ContractSignAuditing>> audits = findContractSignAuditing("signRtt", contractSignRttId);
                        if (audits == null || audits.isEmpty()) {
                            saveContractSignAuditingProcess("signRtt", contractSignRttId);
                            audits = findContractSignAuditing("signRtt", contractSignRttId);
                        }
                        v.setAudits(audits);
                    }
                }
                //@}
            }
        }
        return pojo;
    }

    @Override
    public LimitedList<ContractSignViewPojo> findContractSignList(Long organizationId, final Long dutyId, final int month, Limit limit, Sorter sorter) {
        LimitedList<ContractSignViewPojo> viewPojos = null;
        List<ContractSign> signs = dataAccessor.findByQuery(ContractSign.class,
                new QueryCreator() {
                    @Override
                    public Query createQuery(Session session) {
                        DynamicQuery dynamicQuery = new DynamicQuery("from ContractSign s where s.state=5 ");
                        dynamicQuery.appendIfNotNull("and s.duty.id = :dutyId", "dutyId", dutyId);
                        if (month != 0) {
                            Date currDate = new Date();
                            Date endDate = null;
                            if (month == 1) {
                                endDate = DateUtil.addMonth(currDate, 1);
                            } else if (month == 2) {
                                endDate = DateUtil.addMonth(currDate, 2);
                            } else if (month == 3) {
                                endDate = DateUtil.addMonth(currDate, 3);
                            } else if (month == 4) {
                                endDate = DateUtil.addMonth(currDate, 6);
                            } else {
                                endDate = DateUtil.addMonth(currDate, 12);
                            }

                            dynamicQuery.append("and s.endDate between :currDate and :endDate", new String[]{"currDate", "endDate"}, new Object[]{currDate, endDate});
                        }

                        return dynamicQuery.build(session);
                    }
                }, limit, sorter);


        if (signs != null && !signs.isEmpty()) {
            viewPojos = new LimitedList<ContractSignViewPojo>();
            for (ContractSign sign : signs) {
                ContractSignViewPojo pojo = new ContractSignViewPojo();
                Long endDays = DateUtil.getDayToCurrdate(sign.getEndDate());
                pojo.setId(sign.getId());
                pojo.setEndDate(endDays);

                if(contract_resign_date <= 0){
                    contract_resign_date = 30;
                }
                if (endDays <= contract_resign_date){   //合同到期提前一个月提醒
                    pojo.setState(9);
                    final Long eid = sign.getEmployeeinfoBase().getId();
                    Long count = dataAccessor.findUnique(Long.class, new QueryCreator() {
                        @Override
                        public Query createQuery(Session session) {
                            Query query = session.createQuery("select count(*) from ContractSign s where s.employeeinfoBase.id=:eid and s.cancel='0'");
                            query.setParameter("eid", eid);
                            return query;
                        }
                    });
                    if(count != null && count > 1){
                        pojo.setState(10);//已续签
                    }
                }
                pojo.setDuty(sign.getDuty());
                // 查找该员工的岗位对应的合同名
                List<String> contractNames = dataAccessor
                        .findByHql(
                                String.class,
                                "select p.contractVersion.contractName from ContractPerson p where p.duty = ?",
                                new Object[]{sign.getDuty()}, null, null);
                if (contractNames != null && !contractNames.isEmpty()) {
                    StringBuffer sb = new StringBuffer();
                    int size = contractNames.size();
                    for (int i = 0; i < size; i++) {
                        sb.append(contractNames.get(i));
                        if (i < size - 1) {
                            sb.append(",");
                        }
                    }
                    pojo.setContractType(sb.toString());
                }
                //查找员工基本信息
                List<EmployeeinfoWork> works = dataAccessor.findByHql(EmployeeinfoWork.class, "from EmployeeinfoWork w where w.baseId=? and w.organization.id=?", new Object[]{sign.getEmployeeinfoBase(), organizationId}, null, null);
                if (works != null && !works.isEmpty()) {
                    EmployeeinfoWork work = works.get(0);
                    pojo.setDepartment(work.getOrganization().getFullName());
                    pojo.setWorkNo(work.getWorkNo());
                    pojo.setName(work.getBaseId().getName());
                    pojo.setWorkId(work.getId());
                } else {
                    continue;
                }
                viewPojos.add(pojo);
            }
        }

        return viewPojos;
    }

    @Override
    public ContractSign getContractSign(Long signId) {
        if (signId == null) {
            return null;
        }
        return dataAccessor.get(ContractSign.class, signId);
    }

    @Override
    public ContractSignZz getContractSignZz(Long signZzId) {
        if (signZzId == null) {
            return null;
        }
        return dataAccessor.get(ContractSignZz.class, signZzId);
    }

    @Override
    public ContractSignRt getContractSignRt(Long signRtId) {
        if (signRtId == null) {
            return null;
        }
        return dataAccessor.get(ContractSignRt.class, signRtId);
    }
    
    @Override
    public ContractSignRtt getContractSignRtt(Long signRtId) {
    	 if (signRtId == null) {
             return null;
         }
         return dataAccessor.get(ContractSignRtt.class, signRtId);
    }
    
    @Override
    public ContractSign getContractSignByEmployeeId(Long employeeId, Long versionId) {
        if (employeeId == null || employeeId <= 0 || versionId == null || versionId <= 0) {
            throw new RuntimeException("【参数异常】【employeeId参数有误】");
        }
        try {
            List<ContractSign> contractSigns = dataAccessor.findByHql(ContractSign.class, "from ContractSign c where c.employeeinfoBase.id = ? and c.version.id=? order by c.id desc", new Object[]{employeeId, versionId}, null, null);
            if (contractSigns != null && contractSigns.size() > 0) {
                return contractSigns.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException("【根据员工编号获取合同签订信息异常】【异常原因："
                    + e.getMessage()
                    + "】【错误地点：ContractServerImpl.getContractSignByEmployeeId】");
        }
    }

    @Override
    public ContractSignZz getContractSignZzByEmployeeId(Long employeeId, Long versionId) {
        if (employeeId == null || employeeId <= 0 || versionId == null || versionId <= 0) {
            throw new RuntimeException("【参数异常】【employeeId参数有误】");
        }
        try {
            List<ContractSignZz> contractSigns = dataAccessor.findByHql(ContractSignZz.class, "from ContractSignZz c where c.employeeinfoBase.id = ? and c.version.id=? order by c.id desc", new Object[]{employeeId, versionId}, null, null);
            if (contractSigns != null && contractSigns.size() > 0) {
                return contractSigns.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException("【根据员工编号获取合同签订信息异常】【异常原因："
                    + e.getMessage()
                    + "】【错误地点：ContractServerImpl.getContractSignByEmployeeId】");
        }
    }
    
    @Override
    public ContractSignRt getContractSignRtByEmployeeId(Long employeeId, Long versionId) {
        if (employeeId == null || employeeId <= 0 || versionId == null || versionId <= 0) {
            throw new RuntimeException("【参数异常】【employeeId参数有误】");
        }
        try {
            List<ContractSignRt> contractSigns = dataAccessor.findByHql(ContractSignRt.class, "from ContractSignRt c where c.employeeinfoBase.id = ? and c.version.id=? order by c.id desc", new Object[]{employeeId, versionId}, null, null);
            if (contractSigns != null && contractSigns.size() > 0) {
                return contractSigns.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException("【根据员工编号获取合同签订信息异常】【异常原因："
                    + e.getMessage()
                    + "】【错误地点：ContractServerImpl.getContractSignRtByEmployeeId】");
        }
    }
    
    @Override
    public ContractSignRtt getContractSignRttByEmployeeId(Long employeeId,
    		Long versionId) {
    	if (employeeId == null || employeeId <= 0 || versionId == null || versionId <= 0) {
            throw new RuntimeException("【参数异常】【employeeId参数有误】");
        }
        try {
            List<ContractSignRtt> contractSigns = dataAccessor.findByHql(ContractSignRtt.class, "from ContractSignRtt c where c.employeeinfoBase.id = ? and c.version.id=? order by c.id desc", new Object[]{employeeId, versionId}, null, null);
            if (contractSigns != null && contractSigns.size() > 0) {
                return contractSigns.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException("【根据员工编号获取合同签订信息异常】【异常原因："
                    + e.getMessage()
                    + "】【错误地点：ContractServerImpl.getContractSignRttByEmployeeId】");
        }
    }


    @Override
    public void saveSignContract(Long reSignContractSignId, final ContractSign contractSign) {
        if (contractSign != null) {
            boolean isCreate = (contractSign.getId() == null || contractSign.getId() <= 0);
            dataAccessor.save(contractSign);
            //续签，修改老数据
            if(reSignContractSignId != null && reSignContractSignId > 0){
                ContractSign old = dataAccessor.get(ContractSign.class, reSignContractSignId);
                if(old != null){
                    old.setState(6);//6已过期
                    dataAccessor.save(old);
                }
            }
            //创建的时候创建一个审核流程
            if(isCreate){
                saveContractSignAuditings(contractSign, 1);
            }
        }
    }

    @Override
    public void saveSignContract(Long reSignContractSignZzId, final ContractSignZz contractSignZz) {
        if (contractSignZz != null) {
            boolean isCreate = (contractSignZz.getId() == null || contractSignZz.getId() <= 0);
            dataAccessor.save(contractSignZz);
            //续签，修改老数据
            if(reSignContractSignZzId != null && reSignContractSignZzId > 0){
                ContractSignZz old = dataAccessor.get(ContractSignZz.class, reSignContractSignZzId);
                if(old != null){
                    old.setState(6);//6已过期
                    dataAccessor.save(old);
                }
            }
            //创建的时候创建一个审核流程
            if(isCreate){
                saveContractSignAuditings(contractSignZz, 1);
            }
        }
    }
    
    @Override
    public void saveSignContract(Long reSignContractSignRtId, final ContractSignRt contractSignRt) {
        if (contractSignRt != null) {
            boolean isCreate = (contractSignRt.getId() == null || contractSignRt.getId() <= 0);
            dataAccessor.save(contractSignRt);
            //续签，修改老数据
            if(reSignContractSignRtId != null && reSignContractSignRtId > 0){
            	ContractSignRt old = dataAccessor.get(ContractSignRt.class, reSignContractSignRtId);
                if(old != null){
                    old.setState(6);//6已过期
                    dataAccessor.save(old);
                }
            }
            //创建的时候创建一个审核流程
            if(isCreate){
                saveContractSignAuditings(contractSignRt, 1);
            }
        }
    }
    
    @Override
    public void saveSignContract(Long reSignContractSignRttId,
    		ContractSignRtt contractSignRtt) {
    	if (contractSignRtt != null) {
            boolean isCreate = (contractSignRtt.getId() == null || contractSignRtt.getId() <= 0);
            dataAccessor.save(contractSignRtt);
            //续签，修改老数据
            if(reSignContractSignRttId != null && reSignContractSignRttId > 0){
            	ContractSignRtt old = dataAccessor.get(ContractSignRtt.class, reSignContractSignRttId);
                if(old != null){
                    old.setState(6);//6已过期
                    dataAccessor.save(old);
                }
            }
            //创建的时候创建一个审核流程
            if(isCreate){
                saveContractSignAuditings(contractSignRtt, 1);
            }
        }
    }

    @Override
    public void updateSignContract(ContractSign contractSign) {
        dataAccessor.update(contractSign);
    }

    @Override
    public void updateSignContract(ContractSignZz contractSignZz) {
        dataAccessor.update(contractSignZz);
    }
    
    @Override
    public void updateSignContract(ContractSignRt contractSignRt) {
    	try {
    		dataAccessor.update(contractSignRt);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
    }
    
    @Override
    public void updateSignContract(ContractSignRtt contractSignRtt) {
    	try {
    		dataAccessor.update(contractSignRtt);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }

    @Override
    public void updateContractSignState(final Long id, final Integer state) {
        if (id == null || state == null) {
            return;
        }
        dataAccessor.batchUpdate(new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                return session.createQuery(String
                        .format("update ContractSign p set p.state =(%s) where p.id=(%s)",
                        state, id));
            }
        });
        if (state == 2) {
            this.saveContractSignAuditingProcess("sign", id);
        }
    }

    @Override
    public List<List<ContractVersionAuditing>> findContractVersionAuditing(Long id) {
        return auditingRepository.findByHql(ContractVersionAuditing.class, "from ContractVersionAuditing ver where ver.contractVersion.id=?", new Object[]{id});
    }

    @Override
    public void saveContractVersioniAuditingProcess(Long contractVersionId) {
        saveContractVersionAuditings(getVersion(contractVersionId), 1);
    }

//创建合同版本审核流程

    private void saveContractVersionAuditings(ContractVersion contractVersion, int auditNo) {
        auditingRepository.saveAuditingProcess(contractVersion, auditNo);
    }

    @Override
    public List<List<ContractSignAuditing>> findContractSignAuditing(String type, Long contractSignId) {
        if(StringUtils.equals("sign", type)){
            return auditingRepository.findByHql(ContractSignAuditing.class, "from ContractSignAuditing ver where ver.contractSign.id=?", new Object[]{contractSignId});
        }else if(StringUtils.equals("signZz", type)){
        	return auditingRepository.findByHql(ContractSignAuditing.class, "from ContractSignAuditing ver where ver.contractSignZz.id=?", new Object[]{contractSignId});
        }else if(StringUtils.equals("signRt", type)){
        	return auditingRepository.findByHql(ContractSignAuditing.class, "from ContractSignAuditing ver where ver.contractSignRt.id=?", new Object[]{contractSignId});
        }else if(StringUtils.equals("signRtt", type)){
        	return auditingRepository.findByHql(ContractSignAuditing.class, "from ContractSignAuditing ver where ver.contractSignRtt.id=?", new Object[]{contractSignId});
        }
        return null;
    }

    @Override
    public void saveContractSignAuditingProcess(String type, Long contractSignId) {
        if(StringUtils.equals("sign", type)){
            saveContractSignAuditings(getContractSign(contractSignId), 1);
        }else if(StringUtils.equals("signRt", type)){
            saveContractSignAuditings(getContractSignRt(contractSignId), 1);
        }else if(StringUtils.equals("signRtt", type)){
            saveContractSignAuditings(getContractSignRtt(contractSignId), 1);
        } else{
            saveContractSignAuditings(getContractSignZz(contractSignId), 1);
        }
    }

    //创建合同签订审核流程
    private void saveContractSignAuditings(ContractSign contractSign, int auditNo) {
        auditingRepository.saveAuditingProcess(contractSign, auditNo);
    }
    private void saveContractSignAuditings(ContractSignZz contractSignZz, int auditNo) {
        auditingRepository.saveAuditingProcess(contractSignZz, auditNo);
    }
    
    private void saveContractSignAuditings(ContractSignRt contractSignRt, int auditNo) {
        auditingRepository.saveAuditingProcess(contractSignRt, auditNo);
    }
    
    private void saveContractSignAuditings(ContractSignRtt contractSignRtt, int auditNo) {
        auditingRepository.saveAuditingProcess(contractSignRtt, auditNo);
    }
}
